<?php

namespace App\Services\Access;

use App\Constants\CodeData;
use App\Dao\AnchorDao;
use App\Dao\AnchorEvaluateDao;
use App\Dao\AppUpgradeDao;
use App\Dao\BannerDao;
use App\Dao\CityIpDao;
use App\Dao\CommonSettingDao;
use App\Dao\IndexActionDao;
use App\Dao\SettingDao;
use App\Exception\MessageException;
use App\Model\Guild;
use App\Model\User;
use App\Model\UserActive;
use App\Utils\FunUtil;
use App\Utils\LoggerUtil;
use App\Utils\MemcacheClient;
use Throwable;
use function Hyperf\Config\config;

class SessionService
{
    public function session(array $param)
    {
        try {
            $times = getMillisecond();
            $uid = $param['uid'] ?? 0;
            $session_id = $param['session_id'] ?? '';
            $from = $param['from'] ?? 1;
            $version_code = $param['version_code'] ?? 0;
            $channel = $param['channel'] ?? '';
            $imei = $param['imei'] ?? '';
            $local_code = $param['local_code'] ?? 0;
            $network_state = $param['network_state'] ?? 0;
            $package = $param['package'] ?? '';
            $phone_brand = $param['phone_brand'] ?? '';
            $param['start_time'] = $times;
            LoggerUtil::write("session", $param);
            $ip = FunUtil::getClientIp();

            //用户登录信息
            $login = $data = [];
            $login['msg'] = [];

            if ($uid <= 0 || empty($session_id)) {
                $env = 0;
                // 获取当前登录环境
                $check = (new AppUpgradeDao())->isHideMaleChatCost($from, $version_code, $channel, $ip, $uid);
                if ($check) {
                    $env = '1';
                }
                $login['result'] = 0;
            } else {
                [$login, $env] = $this->logined($uid, $session_id, $from, $version_code, $channel, $imei, $login, $network_state, $package, $phone_brand, $ip);
            }

            if (!empty($userInfo)) {
                IndexActionDao::getInstance()->deleteInitCache($userInfo);
            }

            $data['login_env'] = $env;
            $data['login'] = $login;
            $setting = SettingDao::getInstance();
            $settingData = $setting->getData();
            $smash_eggs_switch = intval($setting->getOne('smash_eggs_switch', $settingData));


            //清理客户端数据
            $cleanConfig = FunUtil::getCleanConfig();
            $data['info_config']['cleaning'] = $cleanConfig;


            // 分享推广
            $data["share"] = array(
                "share_title" => $setting->getOne('share_title', $settingData),
                "share_desc" => $setting->getOne('share_desc', $settingData),
                "share_photo" => $setting->getOne('share_photo', $settingData),
                "share_poster" => [
                    "https://magoo.oss-ap-southeast-1.aliyuncs.com/static/p1.png",
                    "https://magoo.oss-ap-southeast-1.aliyuncs.com/static/p2.png",
                    "https://magoo.oss-ap-southeast-1.aliyuncs.com/static/p3.png"
                ]
                // "share_url" => $setting->getOne('share_url', $settingData),
            );

            // $share_url = $setting->getOne('share_url', $settingData);
            $share_url = "https://www.lagoapp.com/TermsOfService.html";

            $data["share"]["share_url"] = $share_url . (strpos($share_url, "?") ? "&" : "?") .
                // "share_title=" . urlencode($data["share"]["share_title"])
                "t=" . time();


            // TODO START
            // $data["other"] = array(
            //     "recharge_list_switch" => intval($setting->getOne('recharge_list_switch', $settingData)),
            //     "call_mass_login_time" => intval($setting->getOne('call_mass_login_time', $settingData)),
            //     'user_lottery_switch' => intval($setting->getOne('user_lottery_switch', $settingData)),
            //     'user_sign_switch' => intval($setting->getOne('user_sign_switch', $settingData)),     // 签到显示
            //     'match_switch' => intval($setting->getOne('match_switch', $settingData)),     // 是否开启心动匹配(男端) 0不开启 1开启
            //     'match_count' => intval($setting->getOne('match_count', $settingData)),   //匹配次数(男端)
            //     'match_wait_time' => intval($setting->getOne('match_wait_time', $settingData)),     // 呼叫等待时间(男端)
            //     'match_required_vip' => intval($setting->getOne('match_required_vip', $settingData)),     // 是否需要VIP(男端)
            //
            //     'match_have_free_time'=>intval($setting->getOne('match_have_free_time', $settingData)),     // 匹配时有金币免费时长
            //     'match_not_free_time'=>intval($setting->getOne('match_not_free_time', $settingData)),     // 匹配时无金币免费时长
            //     'match_popup_time'=>intval($setting->getOne('match_popup_time', $settingData)),     // 匹配时充值弹窗时间
            //     'match_free_count'=>intval($setting->getOne('match_free_count', $settingData)),     // 匹配免费次数（当日超过该次数需要开通vip,废弃）
            //     'match_force_pay'=>1,       // 匹配强制付费
            //     'match_first_recharge_count'=>3,       // 首次充值获得匹配次数
            //
            //     'match_female_switch' => intval($setting->getOne('match_female_switch', $settingData)),     // 是否开启心动匹配(女端) 0不开启 1开启
            //     'match_female_count' => intval($setting->getOne('match_female_count', $settingData)),     // 匹配次数(女端)
            //     'match_female_wait_time' => intval($setting->getOne('match_female_wait_time', $settingData)),     // 呼叫等待时间(女端)
            //     'match_female_required_vip' => intval($setting->getOne('match_female_required_vip', $settingData)),     // 是否需要VIP(女端)
            //     'match_gift_count' => intval($setting->getOne('match_gift_count', $settingData)),
            //
            // );
            // TODO END

            //公告
            if (intval($setting->getOne('notice_show', $settingData)) == 1 && $login['result'] == 1) {
                if (intval($setting->getOne('notice_rate', $settingData)) == 1) { // 每次上线
                    $data['other']['notice_content'] = $setting->getOne('notice_content', $settingData);
                } else { // 首次上线
                    $notice_content = MemcacheClient::getInstance()->get("notice_content_" . $uid);
                    if ($notice_content === false) {
                        $data['other']['notice_content'] = $setting->getOne('notice_content', $settingData);
                        $time = strtotime(date('Y-m-d', strtotime('+1 day'))) - time();
                        MemcacheClient::getInstance()->set("notice_content_" . $uid, $setting->getOne('notice_content', $settingData), $time);
                    }
                }
            }

            if (isset($userInfo) && $userInfo['register_call_force_vip'] == 1 && $userInfo['noble'] == 0) {
                $data['firstGift']['force_vip'] = 1;
                //$data['call']['call_force_vip'] = 1;
            }
            if (isset($userInfo)) {
                // $guildModel = new Guild();
                // $anchorModel = new AnchorModel();
                if (isset($userInfo['id'])) {
                    // $anchor = $anchorModel->findAnchorInfoCache($userInfo['id']);
                    $anchor = AnchorDao::getInstance()->findAnchorInfoCache($userInfo['id']);
                    if ($anchor) {
                        $guild = Guild::query()->where('guild_num', $anchor['guild_num'])->first();
                        $data['other']['is_family'] = (isset($guild) && $guild['rate'] > 0) ? 1 : 0;
                    } else {
                        $data['other']['is_family'] = 0;
                    }
                } else {
                    $data['other']['is_family'] = 0;
                }
            } else {
                $data['other']['is_family'] = 0;
            }

            // 印象列表,标签
            $evaluate = AnchorEvaluateDao::getInstance()->getData();
            $data['evaluate'] = $evaluate;

            $data['pay_jump_urls'] = ["weixin://wap/pay", "alipays://", "alipay://", "alipayqr://platformapi/startapp", "https://mapi.alipay.com"];

            if ($local_code > 0) {
                $data["noble"]["phone_fare_switch"] = 0;
            }


            // TODO
            // if (!empty($userInfo) && $userInfo['sex'] == 1) {
            //     intval($setting->getOne('match_switch', $settingData)) && $data['index_option'][] = ['title' => "视频速聊", 'url' => '', 'icon' => 'https://image.iyliao.cn/icon/suliao1.png'];
            //     intval($setting->getOne('active_switch', $settingData)) && $data['index_option'][] = ['title' => "活动中心", 'url' => '', 'icon' => 'https://image.iyliao.cn/icon/huodong2.png'];
            //     intval($setting->getOne('task_switch', $settingData)) && $data['index_option'][] = ['title' => "我的任务", 'url' => '', 'icon' => 'https://image.iyliao.cn/icon/renwu2.png'];
            //     intval($setting->getOne('invite_female_switch', $settingData)) && $data['index_option'][] = ['title' => "邀请有礼", 'url' => "https://invitation.activity.iyliao.cn/", 'icon' => 'https://image.iyliao.cn/icon/youli2.png'];
            // }
            // if (!empty($userInfo) && $userInfo['sex'] == 2) {
            //     intval($setting->getOne('match_female_switch', $settingData)) && $data['index_option'][] = ['title' => "视频速聊", 'url' => '', 'icon' => 'https://image.iyliao.cn/icon/suliao2.png'];
            //     intval($setting->getOne('active_female_switch', $settingData)) && $data['index_option'][] = ['title' => "活动中心", 'url' => '', 'icon' => 'https://image.iyliao.cn/icon/huodong2.png'];
            //     // intval($setting->getOne('task_switch', $settingData)) && $data['index_option'][] = ['title' => "我的任务", 'url' => '', 'icon' => 'https://image.iyliao.cn/icon/renwu2.png'];
            //     intval($setting->getOne('invite_female_switch', $settingData)) && $data['index_option'][] = ['title' => "邀请有礼", 'url' => "https://invitation.activity.iyliao.cn/", 'icon' => 'https://image.iyliao.cn/icon/youli2.png'];
            // }
            // TODO END

            // }else {
            //
            //     // 首页顶部入口
            //     if (!empty($userInfo) && $userInfo['sex'] == 1) {
            //         intval($setting->getOne('match_switch', $settingData)) && $data['index_option'][] = ['title' => "视频速聊", 'url' => '', 'icon' => 'https://image.iyliao.cn/icon/%E8%A7%86%E9%A2%91%E9%80%9F%E8%81%8A%402x.png'];
            //         intval($setting->getOne('active_switch', $settingData)) && $data['index_option'][] = ['title' => "活动中心", 'url' => '', 'icon' => 'https://image.iyliao.cn/icon/%E6%B4%BB%E5%8A%A8%E4%B8%AD%E5%BF%83%402x.png'];
            //         intval($setting->getOne('task_switch', $settingData)) && $data['index_option'][] = ['title' => "我的任务", 'url' => '', 'icon' => 'https://image.iyliao.cn/icon/%E6%88%91%E7%9A%84%E4%BB%BB%E5%8A%A1%402x.png'];
            //         // intval($setting->getOne('invite_switch', $settingData)) && $data['index_option'][] = ['title' => "邀请有礼", 'url' => HOST . "/app/h5/active/invite_user.php", 'icon' => 'https://image.iyliao.cn/icon/%E9%82%80%E8%AF%B7%E6%9C%89%E7%A4%BC%402x.png'];
            //     }
            //     if (!empty($userInfo) && $userInfo['sex'] == 2) {
            //         intval($setting->getOne('match_female_switch', $settingData)) && $data['index_option'][] = ['title' => "视频速聊", 'url' => '', 'icon' => 'https://image.iyliao.cn/icon/%E8%A7%86%E9%A2%91%E9%80%9F%E8%81%8A%402x.png'];
            //         intval($setting->getOne('active_female_switch', $settingData)) && $data['index_option'][] = ['title' => "活动中心", 'url' => '', 'icon' => 'https://image.iyliao.cn/icon/%E6%B4%BB%E5%8A%A8%E4%B8%AD%E5%BF%83%402x.png'];
            //         // intval($setting->getOne('invite_female_switch', $settingData)) && $data['index_option'][] = ['title' => "邀请有礼", 'url' => HOST . "/app/h5/active/invite_user.php", 'icon' => 'https://image.iyliao.cn/icon/%E9%82%80%E8%AF%B7%E6%9C%89%E7%A4%BC%402x.png'];
            //     }
            // }


            // TODO START
            // // 首页顶部导航条
            // $data['tab_item'] = [
            //     ['title' => '推荐', 'type' => 1],
            //     // ['title'=>'在线','type'=>4],
            //     // ['title'=>"密友",'type'=>3],
            //     // ['title'=>'关注','type'=>5]
            // ];
            //
            // if($userInfo['sex']==1){
            //     $data['tab_item'] = [
            //         ['title' => '推荐', 'type' => 1],
            //         // ['title'=>'在线','type'=>4],
            //         // ['title'=>"密友",'type'=>3],
            //         // ['title'=>'关注','type'=>5]
            //     ];
            // }
            //
            // // 各种活动规则
            // $data['active_rules']=require_once(ROOT_PATH.'/configs/config.rules.php');
            //
            // // 首页底部导航开关
            // $data['bottom_nav_switch'] = [
            //     ['title' => '首页', 'status' => 1],
            //     ['title' => '视频', 'status' => 1],
            //     ['title' => '发现', 'status' => 1],
            //     ['title' => '消息', 'status' => 1],
            //     ['title' => '我的', 'status' => 1]
            // ];
            // TODO END

            $appUpgrade = new AppupgradeDao();

            $data['agreement'] = [
                'agreement' => config('custom.agreement'),  //用户协议
                'specification' => config('custom.specification'),  //平台行为规范,google的没有，先用用户协议代替
                'privacy' => config('custom.privacy')  //隐私政策
            ];

            // 拨打视频等待时间（秒） 调用通知对方接口
            $data['call']["call_wait_notice"] = 20;

            // 平台客服链接
            $data['customer_service_url'] = HOST . '/app/h5/help.php';
            if ($appUpgrade->isHideCall($from, $version_code, $channel)) {
                $data['customer_service_url'] = $data['customer_service_url'] . "?is_audit=1";
            }

            // 男用户首次充值开关（0开启 1关闭）
            $data['first_recharge'] = $setting->getOne('first_recharge', $settingData);

            if ($package == "com.fdapp.mylove") {
                $data['auto_show_first_recharge'] = 1; // 是否弹出首充弹框 0否 1是
            } else {
                $data['auto_show_first_recharge'] = 0;
            }

            $ad_data = BannerDao::getInstance()->getOnlineList($from, $version_code, 3, [], $package, 5, 0, $channel);
            if (empty($ad_data)) {
                $data['open_ad'] = null;
            } else {
                $data['open_ad'] = [
                    'ad_data' => $ad_data,
                    'times' => 5
                ];
            }
            $data['yunxin_appkey'] = config('yunxin.appkey');

            // 系统维护开关
            $data['system_mend'] = CommonSettingDao::getInstance()->getValue('SYSTEM_MEND', '0');
            $data['system_mend_desc'] = "系统正在维护中";

            LoggerUtil::write("session", ['end_time' => getMillisecond() - $times]);
            return formatData($data);
        } catch (Throwable $e) {
            LoggerUtil::write("session", ['request' => $param, 'msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            throw new MessageException('网络异常，稍后再试！', CodeData::NO_PROMPT);
        }
    }

    /**
     * Note - 已经登录过的用户
     * DateTime 2024/7/18 18:24
     * User Admin
     * @param $uid
     * @param $session_id
     * @param $from
     * @param $version_code
     * @param $channel
     * @param $imei
     * @param $login
     * @param $network_state
     * @param $package
     * @param $phone_brand
     * @param $ip
     * @return mixed
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    private function logined($uid, $session_id, $from, $version_code, $channel, $imei, $login, $network_state, $package, $phone_brand, $ip)
    {
        $env = 0;
        $userInfo = FunUtil::checkUser($uid, $session_id);
        if (empty($userInfo)) {
            $login['result'] = 2;    // 已经在其他机器登录
        } elseif ($userInfo['isdel'] == 1) {
            $login['result'] = 3;    // 该用户已被删除
        } elseif ($userInfo['isdel'] == 2) {
            $login['result'] = 4;    // 该用户资料未完善
            $login['msg'] = $userInfo;
        } else if ($userInfo['sex'] == 2 && FunUtil::gagUserChat($uid)) {
            $login['result'] = 30;    // 风险账号，人脸验证后继续使用
            $login['msg'] = $userInfo;
        } else {
            $login['result'] = '1';

            // 获取当前登录环境
            $check = (new AppUpgradeDao())->isHideMaleChatCost($from, $version_code, $userInfo['channel'] ?: $channel, $ip, $uid);
            if ($check) {
                $env = '1';
            }

            $userInfo['login_env'] = $env;    // 0正常 1审核环境

            $login['msg'] = $userInfo;

            $updates = array('login_time' => time(), 'login_env' => $env, 'version_code' => $version_code, 'package' => $package, 'last_login_ip' => $ip);
            if (empty($userInfo['channel'])) {
                $updates['channel'] = $channel;
            }
            $userInfo['ext2'] && $ext2 = json_decode(json_encode($userInfo['ext2']), true);
            !empty($phone_brand) && $ext2['phone_brand'] = $phone_brand;
            $network_state > 0 && $ext2['network_state'] = $network_state;
            //注册后第一次
            if (MemcacheClient::getInstance()->get('register_script_list_uid_' . $uid)) {
                $ipCache = CityIpDao::getInstance()->getProvinceCity($ip);
                $updates['province'] = !empty($ipCache['province']) ? $ipCache['province'] : '';
                $updates['city'] = !empty($ipCache['city']) ? $ipCache['city'] : '';
            }

            //短信召回
            FunUtil::smsRecall($userInfo['id'], $userInfo['phone'], $updates['login_time']);
            //修改用户登录时间
            User::query()->where('id', $userInfo['id'])->update($updates);
            $result = UserActive::query()->select(['id'])->where('date', date('Y-m-d'))->where('uid', $uid)->where('imei', $imei)->where('ip', $ip)->get()->toArray();

            if (empty($result)) {
                $data1 = array('date' => date('Y-m-d'), 'ip' => $ip, 'uid' => $uid, 'imei' => $imei, 'channel' => $channel, 'ctime' => time());
                UserActive::query()->insert($data1);
            }

            if ($userInfo['is_binding'] == 0 && $userInfo['sex'] == 2) {
                $login['result'] = 5;//手机没绑定
            }
        }

        return [$login, $env];
    }


}